﻿using System.Data;
using System.Text;

namespace Common
{
    /// <summary>
    /// DataTable拓展方法
    /// </summary>
    public static class DataTableExtension
    {
        /// <summary>
        /// 将表格的数据写入本地csv文件
        /// </summary>
        /// <param name="dataTable"> 表格 </param>
        /// <param name="filePath">  本地文件路径 </param>
        public static void WriteToCsvFile(this DataTable dataTable, string filePath)
        {
            StringBuilder fileContent = new StringBuilder();

            foreach (var col in dataTable.Columns)
            {
                fileContent.Append(col.ToString() + ",");
            }

            fileContent.Replace(",", System.Environment.NewLine, fileContent.Length - 1, 1);

            foreach (DataRow dr in dataTable.Rows)
            {
                foreach (var column in dr.ItemArray)
                {
                    fileContent.Append("\"" + column.ToString() + "\",");
                }

                fileContent.Replace(",", System.Environment.NewLine, fileContent.Length - 1, 1);
            }

            System.IO.File.WriteAllText(filePath, fileContent.ToString());
        }
    }
}